package com.leenleda.ips.widget;

import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.leenleda.ips.R;
import com.leenleda.ips.databinding.DialogInputBinding;
import com.leenleda.ips.net.AEvent;
import com.leenleda.ips.util.LogUtils;
import com.leenleda.ips.util.Utils;

import java.util.ArrayList;
import java.util.List;

public class DialogInput implements View.OnTouchListener, View.OnFocusChangeListener, ScannerKeyEventHelper.OnScanSuccessListener {

    private String tag = "DialogInput";

    private Dialog dialog;
    private Context context;
    private OnClickListener listener;
    private DialogInputBinding binding;
    /**
     * @param context
     */
    public DialogInput(final Context context, OnClickListener onClickListener) {
        this.context = context;
        this.listener = onClickListener;
        binding = DialogInputBinding.inflate(LayoutInflater.from(context));
        dialog = new Dialog(context, R.style.custom_dialog);// 创建自定义样式dialog

        Window window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE;
        window.setAttributes(params);
        window.setGravity(Gravity.CENTER);

        dialog.setCancelable(false);// 可以用“返回键”取消
        dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        dialog.setContentView(binding.getRoot(), new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));// 设置布局
        initView();
    }

    private List<View> viewList = new ArrayList<>();
    private void initView(){
        viewList.clear();
        viewList.add(binding.key.button0);
        viewList.add(binding.key.button1);
        viewList.add(binding.key.button2);
        viewList.add(binding.key.button3);
        viewList.add(binding.key.button4);
        viewList.add(binding.key.button5);
        viewList.add(binding.key.button6);
        viewList.add(binding.key.button7);
        viewList.add(binding.key.button8);
        viewList.add(binding.key.button9);
        viewList.add(binding.key.buttonDelete);
        viewList.add(binding.key.buttonDot);

        viewList.add(binding.dialogClear);
        viewList.add(binding.dialogSure);
        viewList.add(binding.dialogClose);
//        viewList.add(binding.dialogPic);
//        viewList.add(binding.dialogVideo);

        for (View view : viewList) {
            view.setOnFocusChangeListener(this);
            view.setOnTouchListener(this);
        }
        binding.dialogSure.requestFocus();

        binding.dialogStr.setOnFocusChangeListener(this);
        binding.dialogStr.setHint(ipStr.isEmpty() ? context.getString(R.string.serverHost) : ipStr);
        dialog.setOnKeyListener((dialogInterface, keyCode, event) -> {
            LogUtils.e(tag, "=====OnKeyListener====" + keyCode);
            if (event.getKeyCode() == KeyEvent.KEYCODE_SHIFT_LEFT
                    || event.getKeyCode() == KeyEvent.KEYCODE_SHIFT_RIGHT) {//扫码枪shift键切换输入
            } else if (event.getAction() != KeyEvent.ACTION_DOWN)
                return false;
            switch (keyCode) {
                case KeyEvent.KEYCODE_DPAD_UP:
                    LogUtils.e(tag, "=====isFocused====" + binding.dialogSure.isFocused());
//                    if (conView) {
//                        binding.view.setVisibility(View.VISIBLE);
//                        binding.key.button1.requestFocus();
//                        return true;
//                    }
                case KeyEvent.KEYCODE_DPAD_LEFT:
                case KeyEvent.KEYCODE_DPAD_RIGHT:
                case KeyEvent.KEYCODE_DPAD_DOWN:
                    return false;
                case KeyEvent.KEYCODE_ENTER:
                case KeyEvent.KEYCODE_DPAD_CENTER:
                    return false;
                case KeyEvent.KEYCODE_BACK:
                    listener.finish();
                    return true;
                case KeyEvent.KEYCODE_0:
                case KeyEvent.KEYCODE_1:
                case KeyEvent.KEYCODE_2:
                case KeyEvent.KEYCODE_3:
                case KeyEvent.KEYCODE_4:
                case KeyEvent.KEYCODE_5:
                case KeyEvent.KEYCODE_6:
                case KeyEvent.KEYCODE_7:
                case KeyEvent.KEYCODE_8:
                case KeyEvent.KEYCODE_9:
                    if (builder.length() > 14)
                        return false;
                    int num = keyCode - 7;
                    builder.append("" + num);
                    binding.dialogStr.setText(builder.toString());
                    return false;
                case KeyEvent.KEYCODE_PERIOD:
                    if (builder.length() > 14)
                        return false;
                    builder.append("." );
                    binding.dialogStr.setText(builder.toString());
                    return false;
                case KeyEvent.KEYCODE_DEL:
                    if (builder.length() > 0)
                        builder.deleteCharAt(builder.length() - 1).toString();
                    binding.dialogStr.setText(builder.toString());
                    return false;
            }
            LogUtils.e(tag, "=====onKey===22======" + keyCode );
            if (mScannerKeyEventHelper == null)
                mScannerKeyEventHelper = new ScannerKeyEventHelper(this);//扫码
            mScannerKeyEventHelper.analysisKeyEvent(event);
            return true;
        });
    }
    private ScannerKeyEventHelper mScannerKeyEventHelper;

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        LogUtils.e(tag, "====ev====" + event.getAction());
        switch (event.getAction()){//鼠标点击
            case MotionEvent.ACTION_DOWN://0
                view.requestFocus();
                buttonInput(view);
                break;
            case MotionEvent.ACTION_UP://1
                return true;
            case MotionEvent.ACTION_MOVE://2
                return true;
        }
        return false;
    }

    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if (hasFocus){
            switch (view.getId()){
//                case R.id.dialog_pic:
//                case R.id.dialog_video:
//                    binding.view.setVisibility(View.GONE);
//                    break;
                default:
                    binding.view.setVisibility(View.VISIBLE);
                    break;
            }
        }
    }

    public interface OnClickListener {
        void onClick(String ipStr);//点击列表监听
        void finish();
    }



    public void show(String ipStr, String state) {
        binding.state.setText(state);
        binding.state.setVisibility(TextUtils.isEmpty(state) ? View.GONE : View.VISIBLE);
        show(ipStr);
    }

    public void show(String ipStr) {
        LogUtils.e("SDNVNSDV", "=====ipStr=======" + ipStr);
        builder.append(Utils.getStringValue(ipStr));
        binding.dialogStr.setText(ipStr);
        show();
    }


    public void show() {
        try {
            if (!dialog.isShowing()) {
                dialog.show();
            }
        } catch (Exception e) {
        }
    }

    public void dismiss() {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    private String ipStr = "";
    private StringBuilder builder = new StringBuilder();
    public void buttonInput(View view){
//        UShared.putLong(Constant.TOUCH_TIME, System.currentTimeMillis() + 60 * 1000);
//        ILog.e(tag, "------buttonInput---=" + UShared.getLong(Constant.TOUCH_TIME));
        switch (view.getId()){
            case R.id.button_delete:
                if (builder.length() > 0)
                    builder.deleteCharAt(builder.length() - 1).toString();
                binding.dialogStr.setText(builder.toString());
                return;
            case R.id.dialog_close:
                if (listener != null)
                    listener.finish();
                return;
            case R.id.dialog_clear:
                builder.setLength(0);
                binding.dialogStr.setText("");
                return;
            case R.id.dialog_sure:
                setServiceIp();
                return;
            default:
                if (builder.length() > 14)
                    return;
                break;
        }
        initInput(view);
    }

    private void initInput(View view){
        switch (view.getId()){
            case R.id.button0:
                builder.append("0");
                break;
            case R.id.button1:
                builder.append("1");
                break;
            case R.id.button2:
                builder.append("2");
                break;
            case R.id.button3:
                builder.append("3");
                break;
            case R.id.button4:
                builder.append("4");
                break;
            case R.id.button5:
                builder.append("5");
                break;
            case R.id.button6:
                builder.append("6");
                break;
            case R.id.button7:
                builder.append("7");
                break;
            case R.id.button8:
                builder.append("8");
                break;
            case R.id.button9:
                builder.append("9");
                break;
            case R.id.button_dot:
                builder.append(".");
                break;
            case R.id.dialog_str:
                binding.view.setVisibility(View.VISIBLE);
                break;
        }
        binding.dialogStr.setText(builder.toString());
    }

    private void setServiceIp(){
        ipStr = builder.toString();
        if (ipStr.isEmpty())
            listener.onClick(context.getString(R.string.serverHost));
        else if (Utils.isBoolIp(builder.toString()))
            listener.onClick(builder.toString());
        else
            AEvent.notifyListener(AEvent.TO_TOAST, true, "请输入IP或包含IP的Json字符串");
    }

    @Override
    public void OnScanSuccess(String barcode) {
        LogUtils.e("SNDVSD", "=======OnScanSuccess====1====" + barcode);
        LogUtils.e("OnScanSuccess", "=======OnScanSuccess=====2===" + barcode);
        String ipStr = barcode;
        if (ipStr.isEmpty())
            return;
        builder.delete(0, builder.length());
        builder.append(ipStr);
        binding.dialogStr.setText(builder.toString());
        LogUtils.e("OnScanSuccess", "=======builder====3===" + builder);
        setServiceIp();
    }
}

